package com.usian.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.usian.admin.mapper.AdChannelMapper;
import com.usian.admin.service.AdChannelService;
import com.usian.model.admin.dtos.ChannelDto;
import com.usian.model.admin.pojos.AdChannel;
import com.usian.model.base.BaseServiceImpl;
import com.usian.model.common.dtos.PageResponseResult;
import com.usian.model.common.dtos.ResponseResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class AdChannelServiceImpl extends BaseServiceImpl<AdChannelMapper, AdChannel> implements AdChannelService {
    @Override
    public ResponseResult findByNameAndPage(ChannelDto channelDto) {
        //参数检测
        if (channelDto==null) return paramError;
        //分页参数查询
        //channelDto.checkParam();
        Page page = new Page(channelDto.getPage(),channelDto.getSize());
        LambdaQueryWrapper<AdChannel> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNoneBlank(channelDto.getName())){
            queryWrapper.like(AdChannel::getName,channelDto.getName());
        }
        IPage result=page(page,queryWrapper);
        //结果封装
        PageResponseResult responseResult = new PageResponseResult(channelDto.getPage(), channelDto.getSize(), (int) result.getTotal());
        responseResult.setData(result.getRecords());
        return responseResult;
    }

    @Override
    public ResponseResult insert(AdChannel channel) {
        //校验参数
        if (channel==null || StringUtils.isBlank(channel.getName())){
            return paramError;
        }
        channel.setCreatedTime(new Date());
        save(channel);
        return paramSuccess;
    }

    @Override
    public ResponseResult update(AdChannel adChannel) {
        //判断数据
        if(adChannel==null || adChannel.getId()==null) {
            return paramError;
        }
        updateById(adChannel);
        return paramSuccess;
    }

    @Override
    public ResponseResult deleteById(Integer id) {
        //看id是否存在
        if (id==null){
            return paramError;
        }
        //判断当前频道是否存在 和 是否有效
        AdChannel channel = getById(id);
        if (channel==null){
            return paramDeleteFail;
        }
        if (channel.getStatus()){
            return paramCantDelete;
        }
//        int a=8/0;
        removeById(id);
        return paramDeleteSuccess;
    }
}
